<template>
    <div class="form regForm">
        <el-form :model="formData" status-icon :rules="formRules" ref="formRef" :show-message="false">
            <el-form-item prop="username">
                <el-input v-model.trim="formData.username" clearable placeholder="用户名" maxLength="32"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model.trim="formData.password" clearable placeholder="密码" maxLength="32"></el-input>
            </el-form-item>
            <el-form-item prop="RepeatPassword">
                <el-input type="password" v-model.trim="formData.RepeatPassword" clearable placeholder="确认密码" maxLength="32"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
                <el-input v-model.trim="formData.phone" placeholder="手机号" clearable maxLength="11"></el-input>
            </el-form-item>
            <el-form-item prop="verifyCode" class="none verifyCode">
                <el-input v-model.trim="formData.verifyCode" clearable placeholder="验证码" maxLength="6"></el-input>
                <button type="button" class="codeBtn right disabled" v-if="isDisabled">发送验证码</button>
                <button type="button" class="codeBtn right" v-else @click="sendCode($event, time)">发送验证码</button>
            </el-form-item>
            <el-form-item class="none">
                <el-checkbox v-model="isAgree" :disabled="!isAgree">
                    <span style="color: #666;">我已阅读并同意</span>
                </el-checkbox>
                <span class="agreeBook" @click="openUserAgree">《用户服务协议》</span>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save('formRef')">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    data() {
        let checkRepeatPass = (rule, value, callback) => {      //校验确认密码是否和密码一致
            if(value !== this.formData['password']) {
                this.$notify({message: '两次输入密码不一致！', type: 'warning', duration: '1500'});
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        }
        return {
            formData: {},
            formRules: {
                username: [{required: true, triggle: 'blur'}],
                password: [{required: true, triggle: 'blur'}],
                RepeatPassword: [{required: true, triggle: 'blur'}, {validator: checkRepeatPass, trigger: 'blur'}],
                phone: [{required: true, triggle: 'blur'}],
                verifyCode: [{required: true, triggle: 'blur'}],
            },
            isDisabled: true,   //是否禁用验证码按钮
            isRunning: false,   //验证码是否正在倒计时
        }
    },
    computed: {
        isAgree: {
            get() {
                return this.$store.state.loginStore.isAgree;
            },
            set(val) {
                //不做任何处理
                this.$store.commit('loginStore/updateIsAgree', val);
            }
        },
        time() {
            return this.$store.state.loginStore.time;
        }
    },
    watch: {
        'formData.phone'(newVal) {  //监听手机号码的位数
            if(this.isRunning) {
                //如果验证码正在倒计时，取消禁用状态
                this.isDisabled = false;
            } else {
                //如果验证码不在倒计时，判断手机号位数是否等于11位，不等于11位就禁用按钮点击
                newVal.length !== 11 ? this.isDisabled = true : this.isDisabled = false;
            }
        },
        isRunning(newVal) {
            if(newVal) {
                //如果验证码正在倒计时，取消禁用状态
                this.isDisabled = false;
            } else {
                //如果验证码不在倒计时，判断手机号位数是否等于11位，不等于11位就禁用按钮点击
                let phone = this.formData['phone'];
                phone.length !== 11 ? this.isDisabled = true : this.isDisabled = false;
            }
        }
    },
    methods: {
        openUserAgree() {       //打开用户协议
            this.$store.commit('loginStore/updateStatus', 5);
        },
        sendCode(ev, time) {        //发送验证码
            //发送验证码之前先校验手机号是否合法
            if(!this.$util.checkPhone(this.formData['phone'])) {
                this.$alert('手机号格式不正确', '注册提示', {
                    confirmButtonText: '确定'
                });
                return false;
            }
            //开始后台校验
            this.$http('verify/phoneRegisterVerify?phone=' + this.formData['phone']).then(res => {
                if(res.data.code == 20001) {
                    this.$alert(res.data.data || '验证码发送成功', '注册提示', {
                        confirmButtonText: '确定'
                    });
                    let timer = null,
                        elem = ev.target;
                    timer = setInterval(() => {
                        if(time <= 1) {
                            clearInterval(timer);
                            elem.innerHTML = '发送验证码';
                            this.isRunning = false;
                        } else {
                            time--;
                            elem.innerHTML = time;
                            this.isRunning = true;
                        }
                    }, 1000);
                } else {
                    this.$alert(res.data.msg || '验证码发送失败', '注册提示', {
                        confirmButtonText: '确定'
                    });
                }
            });
        },
        save(formName) {        //注册
            //注册前判断用户协议是否勾选了
            if(!this.isAgree) {
                this.$alert('阅读并同意用户服务协议', '注册提示', {
                    confirmButtonText: '确定',
                });
                return false;
            }
            //注册数据提交到后台
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$http({
                        method: 'post',
                        url: 'register/insert',
                        params: this.formData
                    }).then(res => {
                        console.log(res)
                        if(res.data.code == 20001) {
                            this.$alert('注册成功', '注册提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    this.$refs[formName].resetFields();     //重置表单
                                    this.$store.commit('loginStore/updateStatus', 2);
                                }
                            });
                        } else {
                            this.$alert(res.data.msg || '注册失败', '注册提示', {
                                confirmButtonText: '确定',
                            });
                        }
                    });
                }
            });
        }
    }
}
</script>
<style scoped>
    .agreeBook {color: #409eff;cursor: pointer;}
    .agreeBook:hover {text-decoration: underline;}
</style>